package com.qipay.sp.excutor.single;

import com.alibaba.fastjson.JSONObject;
import com.qipay.baas.model.Order;
import com.qipay.scalar.type.ApiTypeEnum;
import com.qipay.sp.excutor.AbstractExcutor;
import com.qipay.utils.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Component
public class SingleAlipayWapExcutor extends AbstractExcutor {

    private final static String API_URL="api_url";


    @Override
    protected ApiTypeEnum getApiTypeEnum() {
        return ApiTypeEnum.WX_WAP_PAY;
    }

    @Override
    protected Map<String, Object> getApiParams(Order order, Map<String, Object> spconfig, Map<String, Object> extendOrderParams) {
        Map<String, Object> apiParams = new HashMap<>();
        apiParams.put("merchant_order_no", order.getTradeNo());
        apiParams.put("pay_type", "1");//支付宝H5
        apiParams.put("trade_amount", new BigDecimal(order.getAmount()).divide(new BigDecimal("100"),2,BigDecimal.ROUND_DOWN));
        return apiParams;
    }

    @Override
    protected Map<String, Object> run(Map<String, Object> spconfig, Map<String, Object> params) throws Exception {
        Object apiUrl = getVal(spconfig, API_URL);
        Object merchantNo= getVal(spconfig, "merchant_no");
        Object notifyUrl= getVal(spconfig, "notify_url");
        Object returnUrl= getVal(spconfig, "return_url");
        Object key= getVal(spconfig, "key");

        params.put("merchant_no",merchantNo);
        params.put("notify_url",notifyUrl);
        params.put("return_url",returnUrl);

        String sign = MD5Util.getSign(params,key.toString());
        params.put("sign",sign);
        String result = sendFormPost(params,apiUrl.toString());
        if (StringUtils.isBlank(result)) {
            throw new Exception("请求个人支付宝宝接口失败");
        }
        Map<String, Object> responseMap = JSONObject.parseObject(result);
        Map<String, Object> resultMap = new HashMap<>();
        if (responseMap != null &&"1".equals(responseMap.get("status").toString()) ) {
            resultMap.put("result_code", "0");
            resultMap.put("redirect_url", responseMap.get("pay_url"));

        }else{
            logger.error("请求个人支付宝接口失败:" + result);
            resultMap.put("result_code", "1");
            resultMap.put("message", "请截图给上游客服：个人支付宝接口请求失败");
        }
        return resultMap;
    }
}
